package com.woniuxy.service.impl;

import com.woniuxy.dao.OrderDao;
import com.woniuxy.entity.Order;
import com.woniuxy.entity.Product;
import com.woniuxy.entity.utils.ResponseEntity;
import com.woniuxy.service.OrderService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: 马宇航
 * @Description: 使用了eureka的方法方式,和之前的手写list区别不大。
 * @DateTime: 22/10/10/0010 17:29
 * @Component: 成都蜗牛学苑
 **/
public class OrderServiceImplEureka implements OrderService {
    private static int times=0;
    @Autowired
    OrderDao orderDao;
    @Autowired
    DiscoveryClient discoveryClient;//服务发现，有消费者去eureka的服务器拉取实例列表
    @Override
    public ResponseEntity addOrder(Integer pid, Integer num) {
        //先通过pid 去查询商品服务中，有没有这个商品，判断库存还够不够num来扣减。
        //这个RestTemplate就是 微服务进行http请求调用的，它可以往别的Springboot中发起请求并获得返回值。
        RestTemplate restTemplate = new RestTemplate();
        List<ServiceInstance> instances = discoveryClient.getInstances("MYH-PRODUCT");
        ServiceInstance serviceInstance = instances.get(times++ % instances.size());
        String url = serviceInstance.getUri().toString();
        ResponseEntity response = restTemplate.getForObject(url+"/product/" + pid, ResponseEntity.class);
        //获取响应体中的数据
        System.out.println(response.get(ResponseEntity.ResponseStatus.DATA.value()));
        //如果响应码是500 说明那边是没这个商品的
        int status = (int) response.get(ResponseEntity.ResponseStatus.CODE.value());
        if (status == 500){
            return ResponseEntity.ERROR;
        }
        Map resultObject = (Map) response.get(ResponseEntity.ResponseStatus.DATA.value());
        Product product = new Product();
        try {
            //自动封装map中的key，进入实体类中resultObject.get(key);
            BeanUtils.populate(product,resultObject);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //判断是否能够成功扣减库存
        if(product.getStock()-num>=0){
//            执行插入方法
            Order order = new Order();
            order.setPid(pid);
            order.setNumber(num);
            order.setPname(product.getName());
            order.setPrice(product.getPrice());
            order.setUid(1);
            order.setUsername("蔡徐坤");
            Order save = orderDao.save(order);
            if (save != null) {
                //订单插入成功后，更新库存 改之后的值 0
                product.setStock(product.getStock()-num);
                restTemplate.put(url+"/product/",product);
            }
        }
        return response;
    }
}
